package com.anyonavinfo.cpaddemo.service.musicplayerservice;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;

import com.anyonavinfo.cpaddemo.Application;

import static android.content.Context.BIND_AUTO_CREATE;

/**
 * Created by ZuiC on 2017/2/1.
 */

public class MusicPlayerServiceManager {

    private Context mContext;
    private static MusicPlayerServiceManager INSTANCE = null;
    private MusicPlayerService musicService;
    private MyMusicConnection musicConn;
    private String TAG = "MusicLog";

    public static MusicPlayerServiceManager getInstance(){
        if (INSTANCE == null) {
            INSTANCE = new MusicPlayerServiceManager();
        }
        return INSTANCE;
    }

    private MusicPlayerServiceManager(){
        mContext = Application.getContextObject();
        bindService();
    }

    private void bindService() {
        Intent musicIntent=new Intent(mContext, MusicPlayerService.class);
        musicConn= new MyMusicConnection();
        mContext.bindService(musicIntent,musicConn,BIND_AUTO_CREATE);
    }


    public void endService() {
        if (musicConn != null) {
            mContext.unbindService(musicConn);
        }
        musicService.stopMusic();
    }

    public MusicPlayerService getService(){
        return musicService;
    }

    private class MyMusicConnection implements ServiceConnection{
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            musicService=((MusicPlayerService.MyBinder) iBinder).getService();
            musicService.onServiceConnected();
        }
        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            musicService=null;
        }
    }
}
